package edu.ustb.efws.base.service;

import edu.ustb.efws.BaseException;
import edu.ustb.efws.base.domain.Detector;
import edu.ustb.efws.base.mapper.DetectorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 设备信息业务服务
 *
 * @author TS Group
 */
@Service
@Transactional(readOnly = true)
public class DetectorService {
    private final DetectorMapper mapper;

    @Autowired
    public DetectorService(DetectorMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 新增设备信息
     *
     * @param t {@link Detector}
     * @return {@link Detector}
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Detector save(Detector t) {
        Date now = new Date();
        t.setCreateTime(now);
        t.setUpdateTime(now);
        mapper.insert(t);
        return t;
    }

    /**
     * 修改设备
     *
     * @param t {@link Detector}
     * @return {@link Detector}
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Detector update(Detector t) {
        if(mapper.update(t) == 0){
            throw new BaseException("修改设备信息错误");
        }
        return mapper.findOne(t.getId());
    }

    /**
     * 删除设备
     *
     * @param id 设备编号
     * @return true 删除成
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean delete(int id) {
        return mapper.delete(id) > 0;
    }

    /**
     * 获取设备信息
     *
     * @param id 设备信息
     * @return {@link Detector}
     */
    public Detector get(int id) {
        Detector t = mapper.findOne(id);
        if(t == null){
            throw new BaseException("设备不存在");
        }
        return  t;
    }

    /**
     * 查询设备记录数
     *
     * @param detectorType 设备类型
     * @param description 设备名称
     * @return 记录数
     */
    public long count(String detectorType, String description) {
        return mapper.count(detectorType, description);
    }

    /**
     * 查询设备
     *
     * @param detectorType 设备类型
     * @param description 设备名称
     * @param offset 查询偏移量
     * @param limit 查询记录数
     * @return 设备记录
     */
    public List<Detector> query(String detectorType, String description, int offset, int limit) {
        return mapper.find(detectorType, description, offset, limit);
    }

    /**
     * 查询所有设备
     *
     * @return 设备集合
     */
    public List<Detector> all(){
        return mapper.findAll();
    }
}
